<?php
/**
 * Logging Classes
 *
 * Classes and interfaces related to logging wikipedia parsings.
 *
 * @author Rob Young
 * @package forage.examples.wikipedia
 */

/**
 * Interface for handling log data
 */
interface Logger
{
  public function log($data);
}

/* Suplementary Logging Classes */
class ConsoleLogger implements Logger
{
  public function log($data)
  {
    if (substr($data, -1)!="\n") {
      $data .= "\n";
    }
    echo $data;
  }
}

abstract class LoggingAction implements WikipediaParserAction
{
  protected $logger, $target, $counter, $tick;
  public function __construct(WikipediaParserAction $target, Logger $logger, $tick=1000)
  {
    $this->counter = 0;
    $this->tick    = $tick;
    $this->logger  = $logger;
    $this->target  = $target;
  }

  public function parsedPage(WikipediaPage $page)
  {
    $this->target->parsedPage($page);
    $this->counter++;
    if ($this->counter%$this->tick==0) {
      $this->log($page);
    }
  }

  abstract function log(WikipediaPage $page);
}

class ProgressLoggingAction extends LoggingAction
{
  private $prefix;

  public function __construct(WikipediaParserAction $target, Logger $logger, $prefix='', $tick=1000)
  {
    parent::__construct($target, $logger, $tick);
    $this->prefix = $prefix;
  }
  public function log(WikipediaPage $page)
  {
    $this->logger->log($this->prefix.$this->counter);
  }
}

class ForageLoggingAction extends LoggingAction
{
  private $forage;
  public function __construct(WikipediaParserAction $target, Logger $logger, Forage $forage, $tick=1000) 
  {
    parent::__construct($target, $logger, $tick);
    $this->forage = $forage;
  }
  public function log(WikipediaPage $page)
  {
    $profiler = $this->forage->profiler;
    $this->logger->log('Profiler: ' . $profiler->rate('add') . ' docs/s (' . $profiler->hits('add') . '/' . $profiler->total('add') . ' - ' . time() . ")");
  }
}
